package com.tanger.im.service.address;

import com.tanger.common.result.ActionResult;
import com.tanger.common.utils.BeanUtils;
import com.tanger.im.entity.ImUserAddress;
import com.tanger.im.mapper.IMUserAddressRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @Description TODO
 * @Author Hchenbin
 * @Date 2023-12-25 15:40
 * @Version 1.0
 */
@Slf4j
@Service
public class IMUserAddressServiceImpl implements IMUserAddressService {

    @Autowired
    private IMUserAddressRepository repository;

    @Override
    public ImUserAddress findOne(Long id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ActionResult save(ImUserAddress vo) {
        ImUserAddress address = findOneByUserId(vo.getUserId());
        if (Objects.isNull(address)) {
            repository.save(vo);
            return ActionResult.buildResultSuccess();
        }
        repository.saveAndFlush(BeanUtils.copyProperties(vo,address));
        return ActionResult.buildResultSuccess();
    }

    @Override
    public ImUserAddress findOneByUserId(Long userId) {
        return repository.findOne(Example.of(new ImUserAddress(userId))).orElse(null);
    }
}
